import {Component, OnInit, ViewEncapsulation, OnDestroy, ViewChild} from '@angular/core';
import {GoodsService} from "../goods.service";
import {Subject} from "rxjs/Rx";
import {ActivatedRoute, Params, Router} from "@angular/router";
import {ToolsService} from "@shared/service/tools/tools.service";
import {AuthService} from "@shared/service/auth/auth.service";
import {Observable} from "rxjs/Observable";
import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {EventsService} from "@core/events/events.service";
import {SeoService} from "@core/seo/seo.service";
import {CanReceiveCouponRespVO, GoodsRespVO} from "@interface/index";


@Component({
  selector: 'seed-goods-detail',
  templateUrl: './goods-detail.component.html',
  styleUrls: ['./goods-detail.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class GoodsDetailComponent implements OnInit, OnDestroy {
  public data: Observable<GoodsRespVO>;
  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public skuList = {};
  private _goodPrice: any;
  public specText = '选择规格';
  public goodsStatusText = '立即购买';
  private _goodsStatus = false;
  public faqkey: string;
  private goodsCateCode1;
  public canBuy = true;   // 产品需求漏掉 goodscode 为V12
  public bizId = ''; // 商品ID（业务ID)
  public dataStore = {
    costPrice: ''
  };
  public stateStore = {
    isCollected: 0 // 是否已收藏（0：否，1：是）
  };
  public params = {
    page: 1,
    rows: 10,
  };
  public param = {
    page: 1,
    rows: 200,
  };
  public pages: number;
  public couponList: Array<CanReceiveCouponRespVO> = [];  // 可领取优惠券列表
  @ViewChild('modal3') modal3;
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  // public modalWrap: any;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private goodsService: GoodsService,
    private tools: ToolsService,
    private events: EventsService,
    private authService: AuthService,
    private auth: AuthService,
    private _seoService: SeoService
  ) {
    this.data = this.goodsService.fetchGoodsDetail(this.route);
    this.route.params.subscribe(params => {
      const goodsCode = params['goodsCode'];
      this.bizId = params['goodsCode'];
      const type = goodsCode.substring(0, 3).toLowerCase();
      if (type === 'v12') {
        this.canBuy = false;
      }
    });
    this.data.subscribe(data => {
      this.handleGoodsStatus(data);
      this.handleGoodsPrice(data);
      this.setTKD(data);
      this.goodsCateCode1 = data.goodsCateCode1;
      this.stateStore.isCollected = data.isFavorite;
    });
    this.getCouponList();
  }

  /**
   * @description 设置TKD
   * @author @ouyqx691
   * @date 2018-4-3
   * @param data
   */
  setTKD(data) {
    this._seoService.setTKD(
      `${data.goodsFullName}`,
      `${data.goodsFullName}_${data.goodsCateName}`,
      `求苗体育聚集各类体育产业IP，包含但不限于体育赛事、体育培训、体育旅游、体育赞助、体育用品等各大板块，
      实现多种资源的聚合与互通, 赛事运营管理、合作机构对接、消费数据统计及线上推广等多服务轻松一键搞定的健康运动服务的互联网平台`
    );
  }
  /**
   * @description 处理商品价格
   * @author @ouyqx691
   * @date 2018-4-3
   * @param data
   */
  handleGoodsPrice(data) {
    const minPrice = this.formatGoodsPrice(data.minSalePrice);
    const maxPrice = this.formatGoodsPrice(data.maxSalePrice);

    this.goodsPrice = data.minSalePrice === data.maxSalePrice ? maxPrice : minPrice + '-' + maxPrice;
  }
  /**
   * @description 格式化价格单位为‘分’
   * @author @chenwh576
   * @date 20170921
   * @param price
   * @returns {number}
   */
  formatGoodsPrice(value) {
    if (value === 0) {
      return '0.00';
    } else {
      const price = (value / 100).toFixed(2);
      const decimal = price.toString().split('.');

      if (!decimal[1]) { // 整数
        return price + '.00';
      } else { // 小数
        return decimal[0] + '.' + decimal[1];
      }
    }
  }

  // 跳转登录页面
  goToLogin() {
    this.router.navigate(['/auth/login']);
  }

  /**
   * @description 处理商品是否能购买状态
   * @author @chenwh576
   * @date 20170921
   * @param val
   */
  set disposeGoodsPurchase(val: boolean) {
    this._goodsStatus = val;
  }

  get disposeGoodsPurchase(): boolean {
    return this._goodsStatus;
  }

  /**
   * @description 点击‘选择规格’事件如果不能购买、已售罄不做操作，
   * 如果没登陆，弹出登陆框，如果登录show选择框
   * @author @chenwh576
   * @date 20170921
   * @param modal
   * @returns {boolean}
   */
  handleSelectedSpecEvent(modal) {
    if (this.disposeGoodsPurchase) {
      return false;
    }

    if (this.isLogin()) {
      if (modal) {
        modal.show();
      }
    } else {
      this.authService.selectGoToLogin();
    }
  }

  isLogin(): boolean {
    return this.authService.isLoggedIn;
  }


  /**
   * @description 判断商品状态是否能购买
   * @author @chenwh576
   * @date 20170921
   * @param data
   * @returns {boolean}
   */
  handleGoodsStatus(data: GoodsRespVO) {
    if (data.status === 1) {
      this.goodsStatusText = '已下架';
      this.disposeGoodsPurchase = true;
      return false;
    }

    if (data.status === 2) {
      this.goodsStatusText = '预览';
      this.disposeGoodsPurchase = true;
      return false;
    }

    if (data.totalStock === 0) {
      this.goodsStatusText = '已售罄';
      this.disposeGoodsPurchase = true;
      return false;
    }
  }

  set goodsPrice(val) {
    this._goodPrice = val;
  }

  get goodsPrice() {
    return this._goodPrice;
  }

  /**
   * @description 获取选择的商品数据
   * @author @chenwh576
   * @date 20170921
   * @param event
   */
  handleSelectedSku(event) {
    if (event) {
      this.skuList = event;
      const costPrice = this.formatGoodsPrice(event.price);
      this.dataStore.costPrice = costPrice;
    }
    this.specText = "已选择：" + this.skuList['attrsName'].join('');
    this.goodsPrice = this.formatGoodsPrice(this.skuList['salePrice']);
  }


  /**
   * @description 点击购买按钮事件判断是否选则过商品详情，如果是直接去支付反之吊起选择商品sku页面
   * @author @chenwh576
   * @date 20170921
   * @param modal
   */
  handlePurchaseEvent(modal) {
    //  if(!this.canBuy){
    //    this.tools.presentConfirm('下载求苗APP，看更多精彩内容！');
    //    return false;
    //  }

    if (this.tools.isEmptyObject(this.skuList)) {
      if (!this.isLogin()) {
        this.authService.selectGoToLogin();
      } else {
        modal.show();
      }
    } else {
      if (this.skuList) {
        this.sendOrderToConfirm(this.skuList);
      }
    }
  }

  /**
   * @description 发送订单
   * @author @chenwh576
   * @date 20170921
   * @Modified 2018-03-07 @zhupw1360
   * @param skuList
   */
  sendOrderToConfirm(skuList) {
    const params = {
      'detailList[0].skuCode': skuList.skuCode,
      'detailList[0].quantity': skuList.quantity,
    };
    //  let pa = 'detailList[0].skuCode=V123001_20170915182616_902_20170915182616_1677&detailList[0].quantity=1';
    this.goodsService.sendOrderToConfirm(params).subscribe(res => {
      const navigationExtrasUrl = {
        skuCode: skuList.skuCode,
        quantity: skuList.quantity,
        goodsCateCode1: this.goodsCateCode1,
      };
/**      const navigationExtrasUrl = `?skuCode=${params['detailList[0].skuCode']}&quantity=
      ${params['detailList[0].quantity']}&goodsCateCode= ${this.goodsCateCode1}`;*/
      if (res.result === '20076') {
        this.disposeGoodsPurchase = true;
        //  return;
      }
      this.goodsService.showGoodsResultMsg(res.result, res.msg, navigationExtrasUrl);
    });
  }

  /**
   * @description 点击进入商品FAQ详情页
   * @author @zhupw1360
   * @date 2017-10-23
   * @date 2017-11-27  修改
   * @param goodsCateCode
   */
  goToGoodsFAQ(goodsCateCode: string) {
    this.router.navigate(['/goods/faq'], {
      queryParams: {faqkey: goodsCateCode}
    });
  }

  /**
   * @description 处理商品收藏
   * @author @ouyqx691
   * @date 2017-12-26
   */
  handleCollect() {
    const data = {
      bizId: this.bizId,
      favoriteType: 3
    }
    if (this.stateStore.isCollected === 0) {
      this.goodsService.addFavorites(data).subscribe((res) => {
        if (res.result === '0') {
          this.stateStore.isCollected = 1;
          this.tools.showToast('收藏成功');
        }
      });
    } else {
      this.goodsService.deleteFavorites(data).subscribe((res) => {
        if (res.result === '0') {
          this.stateStore.isCollected = 0;
          this.tools.showToast('已取消收藏');
        }
      });
    }
  }

  /**
   * @description 获取优惠券列表
   * @author @zhupw1360
   * @date 2018-01-02
   * @param params {  page , rows }
   */
  getCouponList() {
    this.goodsService.getCouponList(this.param)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data && res.data.list.length > 0) {
        this.infiniteScroll.enable(false);
        /*        this.params.page++;
                this.infiniteScroll.complete();
                if (!res.data.hasNextPage) {
                  this.infiniteScroll.enable(false);
                }
                this.pages = res.data.pages;*/
        this.couponList = [...this.couponList, ...res.data.list];
      }
    });
  }

  /**
   * @description 改变优惠券领取状态
   * @author @zhupw1360
   * @date 2018-01-02
   * @param params {  page , rows } ，i
   */
  changeCouponStatus(i) {
    if (this.auth.hasLoggedIn()) {
      if (this.couponList[i].useStatus === 0) {
        this.goodsService.postTakeCoupon({batchId: this.couponList[i].batchId})
          .takeUntil(this.ngUnsubscribe).subscribe(res => {
          if (res.result === '0') {
            this.couponList[i].useStatus = 1; // 是否领用过优惠券
            this.tools.showToast('领取成功');
          }
        });
      }
    } else {
      this.tools.presentConfirm('此操作需要登录,是否前往登录', 1, this.goToLogin.bind(this));
      return;
    }
  }

  modalShow() {
    this.modal3.show();
/*    if (this.params.page <= this.pages) {
      this.getCouponList();
    }*/
  }

  // 关闭模态框
  closeModal() {
    this.events.publish('modal:close');
  }

  ngOnInit() {
    /**
     * @description 清除之前购买选择的地址序号
     * @author @chensk740
     * @date 20170925
     */
    localStorage.removeItem('addressIndex');
    // this.modalWrap = this.document.querySelector('#couponWrap');
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

}
